package core

import (
	"time"
)

type Core struct {
	Signal            *Signal
	Serves            []ISv
	initializedServes []ISv // 执行过init的Serve
	SvTime            time.Time
	MsgExecMap        map[MsgType]func(*Msg) //事件类型回调列表
	MsgChan           chan *Msg              //主事件队列
}

var _Core = newCore()

func newCore() *Core {
	co := new(Core)
	co.Signal = NewSignal()
	co.MsgExecMap = make(map[MsgType]func(*Msg))
	co.MsgChan = make(chan *Msg, 1024)
	return co
}

// AddSv 向core中添加Sv
func (co *Core) AddSv(servers ...ISv) {
	for _, server := range servers {
		co.Serves = append(co.Serves, server)
	}
}

// StartSv start all registered Serves
func (co *Core) StartSv() {
	//if len(co.Serves) == 0 {
	//	log.Panic("no server add!!!")
	//}

	defer func() {
		// FILO
		for index := len(co.initializedServes) - 1; index >= 0; index-- {
			destroy(co.initializedServes[index])
		}
		close(co.Signal.Stopped)
	}()

	for _, server := range co.Serves {
		co.initializedServes = append(co.initializedServes, server)
		server.Init()
		// 这里的网络层要和依赖区分开
		go server.Run()
		//coroutine.Go(func() { server.Run() })
	}

	// 主循环
	go co.RunMsg()

	<-co.Signal.Stop
}

// safety destroy server
func destroy(server ISv) {
	defer func() {
		if err := recover(); err != nil {
		}
	}()
	server.Destroy()
}
